package org.thanos.demo.realm;


import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.thanos.demo.entity.SysRole;
import org.thanos.demo.entity.SysUser;
import org.thanos.demo.entity.SysUserRole;
import org.thanos.demo.service.menu.SysMenuService;
import org.thanos.demo.service.role.SysRoleMenuService;
import org.thanos.demo.service.role.SysRoleService;
import org.thanos.demo.service.user.SysUserRoleService;
import org.thanos.demo.service.user.SysUserService;

import java.util.*;


public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    /**
     * 验证权限
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        SysUserRole sysUserRole = sysUserRoleService.selectByUserId(sysUser.getId());
        SysRole sysRole = sysRoleService.selectById(sysUserRole.getRoleId());
        if (Objects.nonNull(sysRole)) {
            // 获取用户角色集,用户权限集
            Set<String> roleSet = Collections.singleton(sysRole.getName());
            List<Integer> menuIds = sysRoleMenuService.selectByRoleId(sysRole.getId());
            Set<String> permissionSet = new HashSet<>(sysMenuService.selectAllPermits(menuIds));
            simpleAuthorizationInfo.setRoles(roleSet);
            simpleAuthorizationInfo.setStringPermissions(permissionSet);
        }
        return simpleAuthorizationInfo;
    }


    /**
     * 验证登录用户
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String loginId = String.valueOf(authenticationToken.getPrincipal());
        String password = new String((char[]) authenticationToken.getCredentials());
        SysUser sysUser = sysUserService.selectByLoginId(loginId);
        if (Objects.isNull(sysUser)) {
            throw new UnknownAccountException("用户不存在！");
        }
        if (!Objects.equals(password, sysUser.getPassword())) {
            throw new IncorrectCredentialsException("密码错误！");
        }
        return new SimpleAuthenticationInfo(sysUser, password, getName());
    }

}
